# -*- coding: utf-8 -*-
from flask import request
from flask_restx import Resource, Namespace, fields
from sqlalchemy.orm.attributes import flag_modified

from app.models.commodity import Commodity
from utils.response import ResponseMaker
from app.models.cart import Cart
from app.models.order import Order
from app.extentions import db
from utils.jwt import JWTUtil


cart_api = Namespace("cart", description="购物车", path="/api/cart")

cart_list_model = cart_api.model('CartListModel', {
    'page_number': fields.Integer(required=True, description='页码', default=1),
    'page_size': fields.Integer(required=True, description='每页数量', default=10),
    'keyword': fields.String(required=False, description='查询关键字，根据商品名称进行搜索'),
})

cart_add_model = cart_api.model('CartAddModel', {
    'commodity_id': fields.Integer(required=True, description='商品id'),
    'commodity_count': fields.Integer(required=True, description='商品数量', default=1),
})

cart_delete_model = cart_api.model('CartDeleteModel', {
    'commodity_id': fields.Integer(required=True, description='商品id')
})

cart_pay_model = cart_api.model('CartPayModel', {
    'commodity_ids': fields.List(fields.Integer, required=True, description='购物车中的商品id列表')
})

cart_list_apimodel = cart_api.model('CartListModel', {
    'page_number': fields.Integer(required=True, description="page number", default=1),
    'page_size': fields.Integer(required=True, description="page size", default=10),
    'keyword': fields.String(required=False, description="key word"),
})


@cart_api.route('/list')
class CartListAPI(Resource):

    @cart_api.doc(body=cart_list_model, description='购物车列表')
    @JWTUtil.verify_token_decorator(request)
    def post(self, *args, **kwargs):
        if not hasattr(request, "user"):
            return ResponseMaker.login_expired()

        commodity_list= []

        cart_items = Cart.query.filter_by(uid=request.user.id).all()
        for cart_item in cart_items:
            commodity_id = cart_item.commodity_id
            commodity_count = cart_item.commodity_count
            commodity = Commodity.query.get(commodity_id)
            commodity_dict = commodity.serialize()
            commodity_dict['commodity_count'] = commodity_count
            commodity_list.append(commodity_dict)

        resp_data = {
            'total': len(commodity_list),
            'data': commodity_list
        }

        return ResponseMaker.success(data=resp_data)


@cart_api.route('/')
class CartDetailAPI(Resource):

    @cart_api.doc(body=cart_add_model, description='添加商品至购物车')
    @JWTUtil.verify_token_decorator(request)
    def post(self, *args, **kwargs):
        if not hasattr(request, "user"):
            return ResponseMaker.login_expired()

        data = request.get_json(force=True)
        commodity_id = data.get('commodity_id')
        commodity_count = data.get('commodity_count')

        cart_item = Cart.query.filter_by(uid=request.user.id, commodity_id=commodity_id).first()

        if not cart_item:
            # 若用户从未添加过此商品，新增记录
            new_cart_item = Cart(uid=request.user.id, commodity_id=commodity_id, commodity_count=commodity_count)
            db.session.add(new_cart_item)
            db.session.commit()
        else:
            # 若用户购物车中已存在此商品，修改商品数量
            cart_item.commodity_count += commodity_count
            db.session.add(cart_item)
            db.session.commit()

        return ResponseMaker.success()

    @cart_api.doc(body=cart_delete_model, description='从购物车中移除商品')
    @JWTUtil.verify_token_decorator(request)
    def delete(self, *args, **kwargs):
        if not hasattr(request, "user"):
            return ResponseMaker.login_expired()

        data = request.get_json(force=True)
        commodity_id = data.get('commodity_id')

        cart_item = Cart.query.filter_by(uid=request.user.id, commodity_id=commodity_id).first()

        if not cart_item:
            # 购物车中没有商品，忽略
            pass
        else:
            db.session.delete(cart_item)
            db.session.commit()

        return ResponseMaker.success()


@cart_api.route('/pay')
class CartPayAPI(Resource):

    @cart_api.doc(body=cart_pay_model, description='购物车结算')
    @JWTUtil.verify_token_decorator(request)
    def post(self, *args, **kwargs):
        data = request.get_json(force=True)
        buy_commodity_ids = data.get('commodity_ids', [])

        # 可结算商品数量
        cart_item_count = Cart.query.filter(Cart.uid==request.user.id).filter(Cart.commodity_id.in_(buy_commodity_ids)).count()
        if cart_item_count == 0:
            return ResponseMaker.no_commodity_for_pay()

        # 生成历史订单
        Order().generate_by_pay(buy_commodity_ids, request.user.id)

        # 删除订单结算的商品
        Cart.query.filter(Cart.uid==request.user.id).filter(Cart.commodity_id.in_(buy_commodity_ids)).delete()
        db.session.commit()

        return ResponseMaker.success()